//
//  ImagePicker.m
//  PigMarket
//
//  Created by mac on 2019/7/22.
//  Copyright © 2019 pigmarket.oc. All rights reserved.
//

#import "ImagePicker.h"
#import <Photos/PHPhotoLibrary.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <TZImagePickerController.h>


@interface ImagePicker ()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UIImagePickerController *cameraPickerVC;
/**
 跟视图
 */
@property (nonatomic , strong) UIViewController *rootViewController;
@end
@implementation ImagePicker

#pragma mark - init method
- (instancetype)init
{
    self = [super init];
    if (self) {
    }
    return self;
}

#pragma mark - 拍照
- (void)takeCameraCallBack:(void (^)(UIImage *))callBack{
    self.takeCameraSuccBlock = callBack;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        [[AlertAction sharedInstance] showAlertWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" confirmBtnTitle:@"设置" confirmBlock:^{
            [self pushPhoneSetting];
        } cancelBlock:nil];
        
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takeCameraCallBack:nil];

                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        [[AlertAction sharedInstance] showAlertWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" confirmBtnTitle:@"设置" confirmBlock:^{
            [self pushPhoneSetting];
        } cancelBlock:^{

        }];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takeCameraCallBack:nil];
        }];
    } else {
        [self pushImagePickerController];
    }
}
// 调用相机
- (void)pushImagePickerController {
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.cameraPickerVC.sourceType = sourceType;
        
        [self.rootViewController presentViewController:self.cameraPickerVC animated:YES completion:^{
            self.cameraPickerVC.delegate = self;
        }];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    if (self.takeCameraSuccBlock) {
        self.takeCameraSuccBlock(image);
    }
    
    //图片存相册
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 相册

- (void)openAlbumCallBack:(void (^)(NSArray<UIImage *> *, NSArray *))callBack{
    NSInteger columNumber = 4;
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxImages columnNumber:columNumber delegate:self pushPhotoPickerVc:YES];
    
    
    imagePickerVC.allowTakePicture = self.allowTakePicture; // 在内部显示拍照按钮
    imagePickerVC.allowTakeVideo = self.allowTakeVideo;   // 在内部显示拍视频按
    imagePickerVC.videoMaximumDuration = self.videoMaximumDuration;
    imagePickerVC.showSelectedIndex = YES;
    
    imagePickerVC.allowPickingVideo = NO;
    imagePickerVC.allowPickingGif = NO;
    imagePickerVC.allowPickingMultipleVideo = NO; // 是否可以多选视频

    
    //圆形裁剪
    imagePickerVC.allowCrop = self.allowCrop;
    imagePickerVC.needCircleCrop = self.needCircleCrop;
    imagePickerVC.cropRect = self.cropRect;
    imagePickerVC.scaleAspectFillCrop = YES;
    
    //外观样式
    imagePickerVC.navigationBar.barTintColor = [UIColor lightGrayColor];
    imagePickerVC.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    imagePickerVC.oKButtonTitleColorNormal = [UIColor greenColor];
    imagePickerVC.navigationBar.translucent = NO;
    imagePickerVC.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVC.showPhotoCannotSelectLayer = YES;
    imagePickerVC.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    
    [imagePickerVC setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        //完成按钮颜色设置
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    
 
    //获取选择的图片
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        callBack(photos,assets);
    }];
    [self.rootViewController presentViewController:imagePickerVC animated:YES completion:nil];
}
//跳转设置页面
- (void)pushPhoneSetting {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}

#pragma mark - setter getter
- (UIImagePickerController *)cameraPickerVC {
    if (!_cameraPickerVC) {
        _cameraPickerVC = [[UIImagePickerController alloc] init];
        _cameraPickerVC.delegate = self;
        _cameraPickerVC.allowsEditing = self.cameraAllowsEditing;
     }
    return _cameraPickerVC;
}
- (UIViewController *)rootViewController {
    if (!_rootViewController) {
        _rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    }
    return _rootViewController;
}
@end

